package com.mamingchao.basic.chain_of_responsibility.v3;

import java.util.ArrayList;
import java.util.List;

/**
 * 这个不支持 链A 拼接链B，所以也不存在 v2里面所叙述的问题
 * 模拟 servlet Filter chain 的责任链实现
 * request 处理顺序是 Filter1，Filter2，Filter3
 * response 处理顺序是 Filter3，Filter2，Filter1
 *
 * Created by mamingchao on 2020/10/13.
 */
public class SimulateServletFilterChain {
    public static void main(String[] args) {

        Request req = new Request();
        req.str = "大家好，我是<script> 马明昌，I am working in viewhigh.com,大家都是996";

        Response res = new Response();
        res.str = "";

        FilterChain fc = new FilterChain();
        fc.addFilter(new ServletUrlFilter())
                .addFilter(new ServletSensitiveWordFilter())
                .addFilter(new ServletScriptFilter());


        fc.doFilter(req,res);
        System.out.println(req);
        System.out.println(res);


    }
}

interface Filter {
    void doFilter(Request req, Response res, FilterChain chain);
}

class Request {
    String str;

    @Override
    public String toString() {
        return "MyRequest{" +
                "str='" + str + '\'' +
                '}';
    }
}

class Response {
    String str;

    @Override
    public String toString() {
        return "MyResponse{" +
                "str='" + str + '\'' +
                '}';
    }
}

class ServletScriptFilter implements Filter {

    @Override
    public void doFilter(Request req, Response res, FilterChain chain) {
        req.str = req.str.replaceAll("<", "[").replaceAll(">", "]");
        chain.doFilter(req,res);
        res.str += " response script filter";
    }
}

class ServletUrlFilter implements Filter {

    @Override
    public void doFilter(Request req, Response res, FilterChain chain) {
        req.str = req.str.replaceAll("viewhigh.com", "www.viewhigh.com");
        chain.doFilter(req,res);
        res.str += " response Url filter";
    }
}

class ServletSensitiveWordFilter implements Filter {
    @Override
    public void doFilter(Request req, Response res, FilterChain chain) {
        req.str = req.str.replaceAll("996", "955");
        chain.doFilter(req,res);
        res.str += " response sensitive word filter";
    }
}


class FilterChain {
    int index = 0;
    private List<Filter> filters = new ArrayList();

    //return this，可以链式调用，这个是个小技巧
    public FilterChain addFilter(Filter f) {
        this.filters.add(f);
        return this;
    }

    public void doFilter(Request req, Response res) {

        if (index == filters.size())
            return;
        Filter f = filters.get(index);
        index ++;
        f.doFilter(req, res,this);
    }
}
